import {
  isObservable,
  isObservableProp
} from 'mobx';
import {
  g3x_defineProperty,
  g3x_defineReadonly
} from "./defineProperties"

/* 107 */
/***/
// root是一个对象，propertyName类似 'aaa.bbb.ccc'

class LocalObject {
  constructor(root, propertyName) {
    this._root = root;
    this._propertyName = propertyName;
    this._props = propertyName.split('.');

    if (this._root._isVue) {
      this._type = 'vue';
      return;
    }

    const lastReactObject = this.lastReactObject;
    const lastPropertyName = this.lastPropertyName;
    const isArray = Array.isArray(lastReactObject);

    if (isArray && isObservable(lastReactObject) && isObservable(lastReactObject[lastPropertyName])) {
      this._type = 'react';
    } else if (!isArray && isObservableProp(lastReactObject, lastPropertyName)) {
      // 无法判断数组索引，会报错
      this._type = 'react';
    } else {
      throw new Error('类型错误！');
    }
  }

// 最终节点
  get d() {
    var l = this._props.length;
    var localObject = this._root;
    for (var i = 0; i < l; ++i) {
      localObject = localObject[this._props[i]];
    }
    return localObject;
  }
  // // 最后一节节点转成索引（假定认为上一级节点是数组，此处则是为了获取其索引，返回值是数字
  // get di() {
  //     return +(this._props[this._props.length - 1]);
  // }
  set d(value) {
    var l = this._props.length - 1;
    var localObject = this._root;
    for (var i = 0; i < l; ++i) {
      localObject = localObject[this._props[i]];
    }
    // 如果不是因为vue，这样写就可以了，但是对于vue来说，要做到让其响应，需要针对数组进行改造
    // localObject[this._props[l]] = value;
    if (Array.isArray(localObject)) {
      localObject.splice(+this._props[l], 1, value); // 为了vue
    } else {
      localObject[this._props[l]] = value;
    }
  }

  get type() {
    return this._type;
  }

// 最终节点的上一级节点（解决vue数组不响应问题时需要）
  get lastReactObject() {
    var l = this._props.length - 1;
    var localObject = this._root;
    for (var i = 0; i < l; ++i) {
      localObject = localObject[this._props[i]];
    }
    return localObject;
  }

  get lastPropertyName() {
    return this._props[this._props.length - 1];
  }
}

export default LocalObject;
